package com.example.event.customer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.example.constant.MqConstants;
import com.example.dto.UserCouponDTO;
import com.example.entity.Coupon;
import com.example.event.BaseEvent;
import com.example.service.CouponService;
import com.example.service.UserCouponService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.example.constant.MqConstants.Exchange.PROMOTION_TOPIC;


/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 监听用户上次登录信息 - 更新用户信息
 * @Date: 2024-05-20-21:04
 */
@Slf4j
@Component
public class CouponReceiveCustomer {


    private String topic = PROMOTION_TOPIC;

    @Resource
    private UserCouponService userCouponService;

    @Resource
    private CouponService couponService;

    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(name = PROMOTION_TOPIC,type = ExchangeTypes.TOPIC),
                    value = @Queue(name = "coupon.receive.queue",durable = "true"),
                    key = MqConstants.Key.COUPON_RECEIVE
            )
    )

    public void listener(String message) {
        try {
            log.info("监听用户领取优惠券信息 topic: {} message: {}", topic, message);
            // 转换对象

            BaseEvent.EventMessage<UserCouponDTO> eventMessage =
                    JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<UserCouponDTO>>() {}.getType());

            UserCouponDTO dto = eventMessage.getData();
            //2.调用业务
            Coupon coupon = couponService.getById(dto.getCouponId());
            if(coupon == null){
                throw new RuntimeException("优惠券不存在");
            }
            userCouponService.checkAndCreateUserCoupon(coupon,dto.getUserId());
        } catch (Exception e) {
            log.error("监听用户领取优惠券信息，消费失败 topic: {} message: {}", topic, message, e);
//            throw e;  // 不用抛异常，消费失败也无伤大雅
        }
    }
}

